<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: #000;
        }
    </style>
</head>

<body>
    <div class="box">


    </div>
    <input type="text" class="input1">
    <script>
        // 1.对于在事件被触发n秒后在执行的回调 延迟执行
        // 2如果在这n秒内在触发事件,重新计时
        var oBox = document.getElementsByClassName('box')[0];

        function test() {
            console.log(1);
        }
        // oBox.onmouseover = test
        oBox.onmouseover = debounce(test, 1000, true)
            //防抖函数
            // 1.是否首次延迟执行
            // 2.n秒之内 触发事件不执行事件处理函数(n秒之内频繁触发事件,计时器会频繁重新开始计时)
        function debounce(fn, time, triggleNow) {
            var t = null,
                res;
            var debounce = function() {
                var _self = this,
                    args = arguments;
                if (t) {
                    clearTimeout(t)
                }
                if (triggleNow) {
                    var exec = !t;
                    t = setTimeout(function() {
                        t = null
                    }, time)

                    if (exec) {
                        res = fn.apply(_self, args)
                    }
                } else {
                    t = setTimeout(function() {
                        res = fn.apply(_self, args)
                    }, time)
                }
                return res
            }
            debounce.remove = function() {
                clearTimeout(t);
                t = null
            }
            return debounce
        }
        //函数防抖:n秒内只要触发事件,就重新计时,事件处理函数的程序将永远不能被执行
        //函数节流 : 事件被触发 n秒之内只执行一次事件处理函数
        var oInput = document.getElementsByClassName('input1')[0];
        oInput.onkeyup = throttle(check, 1000)

        function check(e) {
            console.log('input');
            console.log(e.target.value);
        }

        function throttle(fn, delay) {
            var t = null,
                begin = new Date().getTime();
            return function() {
                var _self = this,
                    args = arguments,
                    cur = new Date().getTime();
                clearTimeout(t);
                if (cur - begin >= delay) {
                    fn.apply(_self, args);
                    begin = cur;
                } else {
                    t = setTimeout(function() {
                        fn.apply(_self, args);
                    }, delay)
                }
            }
        }
    </script>
</body>

</html>